* Fixed a bug that would occour if $wgCapitalLinks was set to false, a user
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.txt
4 *
5 * @package MediaWiki
6 */
7
8 /**
9 *
10 */
11 require_once( 'WatchedItem.php' );
12
13 # Number of characters in user_token field
14 define( 'USER_TOKEN_LENGTH', 32 );
15
16 # Serialized record version
17 define( 'MW_USER_VERSION', 2 );
18
19 /**
20 *
21 * @package MediaWiki
22 */
23 class User {
24 /**#@+
25 * @access private
26 */
27 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
28 var $mEmailAuthenticated;
29 var $mRights, $mOptions;
30 var $mDataLoaded, $mNewpassword;
31 var $mSkin;
32 var $mBlockedby, $mBlockreason;
33 var $mTouched;
34 var $mToken;
35 var $mRealName;
36 var $mHash;
37 var $mGroups;
38 var $mVersion; // serialized version
39
40 /** Construct using User:loadDefaults() */
41 function User() {
42 $this->loadDefaults();
43 $this->mVersion = MW_USER_VERSION;
44 }
45
46 /**
47 * Static factory method
48 * @param string $name Username, validated by Title:newFromText()
49 * @return User
50 * @static
51 */
52 function newFromName( $name ) {
53 $u = new User();
54
55 # Clean up name according to title rules
56
57 $t = Title::newFromText( $name );
58 if( is_null( $t ) ) {
59 return NULL;
60 } else {
61 $u->setName( $t->getText() );
62 $u->setId( $u->idFromName( $t->getText() ) );
63 return $u;
64 }
65 }
66
67 /**
68 * Factory method to fetch whichever use has a given email confirmation code.
69 * This code is generated when an account is created or its e-mail address
70 * has changed.
71 *
72 * If the code is invalid or has expired, returns NULL.
73 *
74 * @param string $code
75 * @return User
76 * @static
77 */
78 function newFromConfirmationCode( $code ) {
79 $dbr =& wfGetDB( DB_SLAVE );
80 $name = $dbr->selectField( 'user', 'user_name', array(
81 'user_email_token' => md5( $code ),
82 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
83 ) );
84 if( is_string( $name ) ) {
85 return User::newFromName( $name );
86 } else {
87 return null;
88 }
89 }
90
91 /**
92 * Serialze sleep function, for better cache efficiency and avoidance of
93 * silly "incomplete type" errors when skins are cached
94 */
95 function __sleep() {
96 return array( 'mId', 'mName', 'mPassword', 'mEmail', 'mNewtalk',
97 'mEmailAuthenticated', 'mRights', 'mOptions', 'mDataLoaded',
98 'mNewpassword', 'mBlockedby', 'mBlockreason', 'mTouched',
99 'mToken', 'mRealName', 'mHash', 'mGroups' );
100 }
101
102 /**
103 * Get username given an id.
104 * @param integer $id Database user id
105 * @return string Nickname of a user
106 * @static
107 */
108 function whoIs( $id ) {
109 $dbr =& wfGetDB( DB_SLAVE );
110 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
111 }
112
113 /**
114 * Get real username given an id.
115 * @param integer $id Database user id
116 * @return string Realname of a user
117 * @static
118 */
119 function whoIsReal( $id ) {
120 $dbr =& wfGetDB( DB_SLAVE );
121 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
122 }
123
124 /**
125 * Get database id given a user name
126 * @param string $name Nickname of a user
127 * @return integer|null Database user id (null: if non existent
128 * @static
129 */
130 function idFromName( $name ) {
131 $fname = "User::idFromName";
132
133 $nt = Title::newFromText( $name );
134 if( is_null( $nt ) ) {
135 # Illegal name
136 return null;
137 }
138 $dbr =& wfGetDB( DB_SLAVE );
139 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
140
141 if ( $s === false ) {
142 return 0;
143 } else {
144 return $s->user_id;
145 }
146 }
147
148 /**
149 * does the string match an anonymous IPv4 address?
150 *
151 * @static
152 * @param string $name Nickname of a user
153 * @return bool
154 */
155 function isIP( $name ) {
156 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",$name);
157 /*return preg_match("/^
158 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
159 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
160 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
161 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
162 $/x", $name);*/
163 }
164
165 /**
166 * Is the input a valid username?
167 *
168 * Checks if the input is a valid username, we don't want an empty string,
169 * an IP address, anything that containins slashes (would mess up subpages),
170 * is longer than the maximum allowed username size or doesn't begin with
171 * a capital letter.
172 *
173 * @param string $name
174 * @return bool
175 */
176 function isValidUserName( $name ) {
177 global $wgContLang, $wgMaxNameChars;
178
179 if ( $name == ''
180 || $this->isIP( $name )
181 || strpos( $name, '/' ) !== false
182 || strlen( $name ) > $wgMaxNameChars
183 || $name != $wgContLang->ucfirst( $name ) )
184 return false;
185 else
186 return true;
187 }
188
189 /**
190 * Is the input a valid password?
191 *
192 * @param string $password
193 * @return bool
194 */
195 function isValidPassword( $password ) {
196 global $wgMinimalPasswordLength;
197 return strlen( $password ) >= $wgMinimalPasswordLength;
198 }
199
200 /**
201 * does the string match roughly an email address ?
202 *
203 * @todo Check for RFC 2822 compilance
204 * @bug 959
205 *
206 * @param string $addr email address
207 * @static
208 * @return bool
209 */
210 function isValidEmailAddr ( $addr ) {
211 # There used to be a regular expression here, it got removed because it
212 # rejected valid addresses.
213 return ( trim( $addr ) != '' ) &&
214 (false !== strpos( $addr, '@' ) );
215 }
216
217 /**
218 * probably return a random password
219 * @return string probably a random password
220 * @static
221 * @todo Check what is doing really [AV]
222 */
223 function randomPassword() {
224 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
225 $l = strlen( $pwchars ) - 1;
226
227 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
228 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
229 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
230 $pwchars{mt_rand( 0, $l )};
231 return $np;
232 }
233
234 /**
235 * Set properties to default
236 * Used at construction. It will load per language default settings only
237 * if we have an available language object.
238 */
239 function loadDefaults() {
240 static $n=0;
241 $n++;
242 $fname = 'User::loadDefaults' . $n;
243 wfProfileIn( $fname );
244
245 global $wgContLang, $wgIP, $wgDBname;
246 global $wgNamespacesToBeSearchedDefault;
247
248 $this->mId = 0;
249 $this->mNewtalk = -1;
250 $this->mName = $wgIP;
251 $this->mRealName = $this->mEmail = '';
252 $this->mEmailAuthenticated = null;
253 $this->mPassword = $this->mNewpassword = '';
254 $this->mRights = array();
255 $this->mGroups = array();
256 $this->mOptions = User::getDefaultOptions();
257
258 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
259 $this->mOptions['searchNs'.$nsnum] = $val;
260 }
261 unset( $this->mSkin );
262 $this->mDataLoaded = false;
263 $this->mBlockedby = -1; # Unset
264 $this->setToken(); # Random
265 $this->mHash = false;
266
267 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
268 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
269 }
270 else {
271 $this->mTouched = '0'; # Allow any pages to be cached
272 }
273
274 wfProfileOut( $fname );
275 }
276
277 /**
278 * Combine the language default options with any site-specific options
279 * and add the default language variants.
280 *
281 * @return array
282 * @static
283 * @access private
284 */
285 function getDefaultOptions() {
286 /**
287 * Site defaults will override the global/language defaults
288 */
289 global $wgContLang, $wgDefaultUserOptions;
290 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
291
292 /**
293 * default language setting
294 */
295 $variant = $wgContLang->getPreferredVariant();
296 $defOpt['variant'] = $variant;
297 $defOpt['language'] = $variant;
298
299 return $defOpt;
300 }
301
302 /**
303 * Get a given default option value.
304 *
305 * @param string $opt
306 * @return string
307 * @static
308 * @access public
309 */
310 function getDefaultOption( $opt ) {
311 $defOpts = User::getDefaultOptions();
312 if( isset( $defOpts[$opt] ) ) {
313 return $defOpts[$opt];
314 } else {
315 return '';
316 }
317 }
318
319 /**
320 * Get blocking information
321 * @access private
322 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
323 * non-critical checks are done against slaves. Check when actually saving should be done against
324 * master.
325 *
326 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
327 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
328 * just slightly outta sync and soon corrected - safer to block slightly more that less.
329 * And it's cheaper to check slave first, then master if needed, than master always.
330 */
331 function getBlockedStatus( $bFromSlave = true ) {
332 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
333
334 if ( -1 != $this->mBlockedby ) { return; }
335
336 $this->mBlockedby = 0;
337
338 # User blocking
339 if ( $this->mId ) {
340 $block = new Block();
341 $block->forUpdate( $bFromSlave );
342 if ( $block->load( $wgIP , $this->mId ) ) {
343 $this->mBlockedby = $block->mBy;
344 $this->mBlockreason = $block->mReason;
345 $this->spreadBlock();
346 }
347 }
348
349 # IP/range blocking
350 if ( !$this->mBlockedby ) {
351 # Check first against slave, and optionally from master.
352 $block = $wgBlockCache->get( $wgIP, true );
353 if ( !$block && !$bFromSlave )
354 {
355 # Not blocked: check against master, to make sure.
356 $wgBlockCache->clearLocal( );
357 $block = $wgBlockCache->get( $wgIP, false );
358 }
359 if ( $block !== false ) {
360 $this->mBlockedby = $block->mBy;
361 $this->mBlockreason = $block->mReason;
362 }
363 }
364
365 # Proxy blocking
366 if ( !$this->isSysop() && !in_array( $wgIP, $wgProxyWhitelist ) ) {
367
368 # Local list
369 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
370 $this->mBlockedby = wfMsg( 'proxyblocker' );
371 $this->mBlockreason = wfMsg( 'proxyblockreason' );
372 }
373
374 # DNSBL
375 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
376 if ( $this->inSorbsBlacklist( $wgIP ) ) {
377 $this->mBlockedby = wfMsg( 'sorbs' );
378 $this->mBlockreason = wfMsg( 'sorbsreason' );
379 }
380 }
381 }
382 }
383
384 function inSorbsBlacklist( $ip ) {
385 global $wgEnableSorbs;
386 return $wgEnableSorbs &&
387 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
388 }
389
390 function inOpmBlacklist( $ip ) {
391 global $wgEnableOpm;
392 return $wgEnableOpm &&
393 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
394 }
395
396 function inDnsBlacklist( $ip, $base ) {
397 $fname = 'User::inDnsBlacklist';
398 wfProfileIn( $fname );
399
400 $found = false;
401 $host = '';
402
403 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
404 # Make hostname
405 for ( $i=4; $i>=1; $i-- ) {
406 $host .= $m[$i] . '.';
407 }
408 $host .= $base;
409
410 # Send query
411 $ipList = gethostbynamel( $host );
412
413 if ( $ipList ) {
414 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
415 $found = true;
416 } else {
417 wfDebug( "Requested $host, not found in $base.\n" );
418 }
419 }
420
421 wfProfileOut( $fname );
422 return $found;
423 }
424
425 /**
426 * Primitive rate limits: enforce maximum actions per time period
427 * to put a brake on flooding.
428 *
429 * Note: when using a shared cache like memcached, IP-address
430 * last-hit counters will be shared across wikis.
431 *
432 * @return bool true if a rate limiter was tripped
433 * @access public
434 */
435 function pingLimiter( $action='edit' ) {
436 global $wgRateLimits;
437 if( !isset( $wgRateLimits[$action] ) ) {
438 return false;
439 }
440 if( $this->isAllowed( 'delete' ) ) {
441 // goddam cabal
442 return false;
443 }
444
445 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
446 $fname = 'User::pingLimiter';
447 $limits = $wgRateLimits[$action];
448 $keys = array();
449 $id = $this->getId();
450
451 if( isset( $limits['anon'] ) && $id == 0 ) {
452 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
453 }
454
455 if( isset( $limits['user'] ) && $id != 0 ) {
456 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
457 }
458 if( $this->isNewbie() ) {
459 if( isset( $limits['newbie'] ) && $id != 0 ) {
460 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
461 }
462 if( isset( $limits['ip'] ) ) {
463 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
464 }
465 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
466 $subnet = $matches[1];
467 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
468 }
469 }
470
471 $triggered = false;
472 foreach( $keys as $key => $limit ) {
473 list( $max, $period ) = $limit;
474 $summary = "(limit $max in {$period}s)";
475 $count = $wgMemc->get( $key );
476 if( $count ) {
477 if( $count > $max ) {
478 wfDebug( "$fname: tripped! $key at $count $summary\n" );
479 if( $wgRateLimitLog ) {
480 @error_log( wfTimestamp( TS_MW ) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
481 }
482 $triggered = true;
483 } else {
484 wfDebug( "$fname: ok. $key at $count $summary\n" );
485 }
486 } else {
487 wfDebug( "$fname: adding record for $key $summary\n" );
488 $wgMemc->add( $key, 1, IntVal( $period ) );
489 }
490 $wgMemc->incr( $key );
491 }
492
493 return $triggered;
494 }
495
496 /**
497 * Check if user is blocked
498 * @return bool True if blocked, false otherwise
499 */
500 function isBlocked( $bFromSlave = false ) {
501 $this->getBlockedStatus( $bFromSlave );
502 return $this->mBlockedby !== 0;
503 }
504
505 /**
506 * Get name of blocker
507 * @return string name of blocker
508 */
509 function blockedBy() {
510 $this->getBlockedStatus();
511 return $this->mBlockedby;
512 }
513
514 /**
515 * Get blocking reason
516 * @return string Blocking reason
517 */
518 function blockedFor() {
519 $this->getBlockedStatus();
520 return $this->mBlockreason;
521 }
522
523 /**
524 * Initialise php session
525 */
526 function SetupSession() {
527 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
528 if( $wgSessionsInMemcached ) {
529 require_once( 'MemcachedSessions.php' );
530 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
531 # If it's left on 'user' or another setting from another
532 # application, it will end up failing. Try to recover.
533 ini_set ( 'session.save_handler', 'files' );
534 }
535 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
536 session_cache_limiter( 'private, must-revalidate' );
537 @session_start();
538 }
539
540 /**
541 * Read datas from session
542 * @static
543 */
544 function loadFromSession() {
545 global $wgMemc, $wgDBname;
546
547 if ( isset( $_SESSION['wsUserID'] ) ) {
548 if ( 0 != $_SESSION['wsUserID'] ) {
549 $sId = $_SESSION['wsUserID'];
550 } else {
551 return new User();
552 }
553 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
554 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
555 $_SESSION['wsUserID'] = $sId;
556 } else {
557 return new User();
558 }
559 if ( isset( $_SESSION['wsUserName'] ) ) {
560 $sName = $_SESSION['wsUserName'];
561 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
562 $sName = $_COOKIE["{$wgDBname}UserName"];
563 $_SESSION['wsUserName'] = $sName;
564 } else {
565 return new User();
566 }
567
568 $passwordCorrect = FALSE;
569 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
570 if( !is_object( $user ) || $user->mVersion < MW_USER_VERSION ) {
571 # Expire old serialized objects; they may be corrupt.
572 $user = false;
573 }
574 if($makenew = !$user) {
575 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
576 $user = new User();
577 $user->mId = $sId;
578 $user->loadFromDatabase();
579 } else {
580 wfDebug( "User::loadFromSession() got from cache!\n" );
581 }
582
583 if ( isset( $_SESSION['wsToken'] ) ) {
584 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
585 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
586 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
587 } else {
588 return new User(); # Can't log in from session
589 }
590
591 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
592 if($makenew) {
593 if($wgMemc->set( $key, $user ))
594 wfDebug( "User::loadFromSession() successfully saved user\n" );
595 else
596 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
597 }
598 return $user;
599 }
600 return new User(); # Can't log in from session
601 }
602
603 /**
604 * Load a user from the database
605 */
606 function loadFromDatabase() {
607 global $wgCommandLineMode;
608 $fname = "User::loadFromDatabase";
609
610 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
611 # loading in a command line script, don't assume all command line scripts need it like this
612 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
613 if ( $this->mDataLoaded ) {
614 return;
615 }
616
617 # Paranoia
618 $this->mId = IntVal( $this->mId );
619
620 /** Anonymous user */
621 if( !$this->mId ) {
622 /** Get rights */
623 $this->mRights = $this->getGroupPermissions( array( '*' ) );
624 $this->mDataLoaded = true;
625 return;
626 } # the following stuff is for non-anonymous users only
627
628 $dbr =& wfGetDB( DB_SLAVE );
629 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
630 'user_email_authenticated',
631 'user_real_name','user_options','user_touched', 'user_token' ),
632 array( 'user_id' => $this->mId ), $fname );
633
634 if ( $s !== false ) {
635 $this->mName = $s->user_name;
636 $this->mEmail = $s->user_email;
637 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
638 $this->mRealName = $s->user_real_name;
639 $this->mPassword = $s->user_password;
640 $this->mNewpassword = $s->user_newpassword;
641 $this->decodeOptions( $s->user_options );
642 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
643 $this->mToken = $s->user_token;
644
645 $res = $dbr->select( 'user_groups',
646 array( 'ug_group' ),
647 array( 'ug_user' => $this->mId ),
648 $fname );
649 $this->mGroups = array();
650 while( $row = $dbr->fetchObject( $res ) ) {
651 $this->mGroups[] = $row->ug_group;
652 }
653 $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups );
654 $this->mRights = $this->getGroupPermissions( $effectiveGroups );
655 }
656
657 $this->mDataLoaded = true;
658 }
659
660 function getID() { return $this->mId; }
661 function setID( $v ) {
662 $this->mId = $v;
663 $this->mDataLoaded = false;
664 }
665
666 function getName() {
667 $this->loadFromDatabase();
668 return $this->mName;
669 }
670
671 function setName( $str ) {
672 $this->loadFromDatabase();
673 $this->mName = $str;
674 }
675
676
677 /**
678 * Return the title dbkey form of the name, for eg user pages.
679 * @return string
680 * @access public
681 */
682 function getTitleKey() {
683 return str_replace( ' ', '_', $this->getName() );
684 }
685
686 function getNewtalk() {
687 global $wgUseEnotif;
688 $fname = 'User::getNewtalk';
689 $this->loadFromDatabase();
690
691 # Load the newtalk status if it is unloaded (mNewtalk=-1)
692 if( $this->mNewtalk == -1 ) {
693 $this->mNewtalk = 0; # reset talk page status
694
695 # Check memcached separately for anons, who have no
696 # entire User object stored in there.
697 if( !$this->mId ) {
698 global $wgDBname, $wgMemc;
699 $key = "$wgDBname:newtalk:ip:{$this->mName}";
700 $newtalk = $wgMemc->get( $key );
701 if( is_integer( $newtalk ) ) {
702 $this->mNewtalk = $newtalk ? 1 : 0;
703 return (bool)$this->mNewtalk;
704 }
705 }
706
707 $dbr =& wfGetDB( DB_SLAVE );
708 if ( $wgUseEnotif ) {
709 $res = $dbr->select( 'watchlist',
710 array( 'wl_user' ),
711 array( 'wl_title' => $this->getTitleKey(),
712 'wl_namespace' => NS_USER_TALK,
713 'wl_user' => $this->mId,
714 'wl_notificationtimestamp != 0' ),
715 'User::getNewtalk' );
716 if( $dbr->numRows($res) > 0 ) {
717 $this->mNewtalk = 1;
718 }
719 $dbr->freeResult( $res );
720 } elseif ( $this->mId ) {
721 $res = $dbr->select( 'user_newtalk', 1, array( 'user_id' => $this->mId ), $fname );
722
723 if ( $dbr->numRows($res)>0 ) {
724 $this->mNewtalk= 1;
725 }
726 $dbr->freeResult( $res );
727 } else {
728 $res = $dbr->select( 'user_newtalk', 1, array( 'user_ip' => $this->mName ), $fname );
729 $this->mNewtalk = $dbr->numRows( $res ) > 0 ? 1 : 0;
730 $dbr->freeResult( $res );
731 }
732
733 if( !$this->mId ) {
734 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
735 }
736 }
737
738 return ( 0 != $this->mNewtalk );
739 }
740
741 function setNewtalk( $val ) {
742 $this->loadFromDatabase();
743 $this->mNewtalk = $val;
744 $this->invalidateCache();
745 }
746
747 function invalidateCache() {
748 global $wgClockSkewFudge;
749 $this->loadFromDatabase();
750 $this->mTouched = wfTimestamp(TS_MW, time() + $wgClockSkewFudge );
751 # Don't forget to save the options after this or
752 # it won't take effect!
753 }
754
755 function validateCache( $timestamp ) {
756 $this->loadFromDatabase();
757 return ($timestamp >= $this->mTouched);
758 }
759
760 /**
761 * Salt a password.
762 * Will only be salted if $wgPasswordSalt is true
763 * @param string Password.
764 * @return string Salted password or clear password.
765 */
766 function addSalt( $p ) {
767 global $wgPasswordSalt;
768 if($wgPasswordSalt)
769 return md5( "{$this->mId}-{$p}" );
770 else
771 return $p;
772 }
773
774 /**
775 * Encrypt a password.
776 * It can eventuall salt a password @see User::addSalt()
777 * @param string $p clear Password.
778 * @param string Encrypted password.
779 */
780 function encryptPassword( $p ) {
781 return $this->addSalt( md5( $p ) );
782 }
783
784 # Set the password and reset the random token
785 function setPassword( $str ) {
786 $this->loadFromDatabase();
787 $this->setToken();
788 $this->mPassword = $this->encryptPassword( $str );
789 $this->mNewpassword = '';
790 }
791
792 # Set the random token (used for persistent authentication)
793 function setToken( $token = false ) {
794 global $wgSecretKey, $wgProxyKey, $wgDBname;
795 if ( !$token ) {
796 if ( $wgSecretKey ) {
797 $key = $wgSecretKey;
798 } elseif ( $wgProxyKey ) {
799 $key = $wgProxyKey;
800 } else {
801 $key = microtime();
802 }
803 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
804 } else {
805 $this->mToken = $token;
806 }
807 }
808
809
810 function setCookiePassword( $str ) {
811 $this->loadFromDatabase();
812 $this->mCookiePassword = md5( $str );
813 }
814
815 function setNewpassword( $str ) {
816 $this->loadFromDatabase();
817 $this->mNewpassword = $this->encryptPassword( $str );
818 }
819
820 function getEmail() {
821 $this->loadFromDatabase();
822 return $this->mEmail;
823 }
824
825 function getEmailAuthenticationTimestamp() {
826 $this->loadFromDatabase();
827 return $this->mEmailAuthenticated;
828 }
829
830 function setEmail( $str ) {
831 $this->loadFromDatabase();
832 $this->mEmail = $str;
833 }
834
835 function getRealName() {
836 $this->loadFromDatabase();
837 return $this->mRealName;
838 }
839
840 function setRealName( $str ) {
841 $this->loadFromDatabase();
842 $this->mRealName = $str;
843 }
844
845 function getOption( $oname ) {
846 $this->loadFromDatabase();
847 if ( array_key_exists( $oname, $this->mOptions ) ) {
848 return trim( $this->mOptions[$oname] );
849 } else {
850 return '';
851 }
852 }
853
854 function setOption( $oname, $val ) {
855 $this->loadFromDatabase();
856 if ( $oname == 'skin' ) {
857 # Clear cached skin, so the new one displays immediately in Special:Preferences
858 unset( $this->mSkin );
859 }
860 $this->mOptions[$oname] = $val;
861 $this->invalidateCache();
862 }
863
864 function getRights() {
865 $this->loadFromDatabase();
866 return $this->mRights;
867 }
868
869 /**
870 * Get the list of explicit group memberships this user has.
871 * The implicit * and user groups are not included.
872 * @return array of strings
873 */
874 function getGroups() {
875 $this->loadFromDatabase();
876 return $this->mGroups;
877 }
878
879 /**
880 * Get the list of implicit group memberships this user has.
881 * This includes all explicit groups, plus 'user' if logged in
882 * and '*' for all accounts.
883 * @return array of strings
884 */
885 function getEffectiveGroups() {
886 $base = array( '*' );
887 if( $this->isLoggedIn() ) {
888 $base[] = 'user';
889 }
890 return array_merge( $base, $this->getGroups() );
891 }
892
893 /**
894 * Remove the user from the given group.
895 * This takes immediate effect.
896 * @string $group
897 */
898 function addGroup( $group ) {
899 $dbw =& wfGetDB( DB_MASTER );
900 $dbw->insert( 'user_groups',
901 array(
902 'ug_user' => $this->getID(),
903 'ug_group' => $group,
904 ),
905 'User::addGroup',
906 array( 'IGNORE' ) );
907
908 $this->mGroups = array_merge( $this->mGroups, array( $group ) );
909 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
910
911 $this->invalidateCache();
912 $this->saveSettings();
913 }
914
915 /**
916 * Remove the user from the given group.
917 * This takes immediate effect.
918 * @string $group
919 */
920 function removeGroup( $group ) {
921 $dbw =& wfGetDB( DB_MASTER );
922 $dbw->delete( 'user_groups',
923 array(
924 'ug_user' => $this->getID(),
925 'ug_group' => $group,
926 ),
927 'User::removeGroup' );
928
929 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
930 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
931
932 $this->invalidateCache();
933 $this->saveSettings();
934 }
935
936
937 /**
938 * A more legible check for non-anonymousness.
939 * Returns true if the user is not an anonymous visitor.
940 *
941 * @return bool
942 */
943 function isLoggedIn() {
944 return( $this->getID() != 0 );
945 }
946
947 /**
948 * A more legible check for anonymousness.
949 * Returns true if the user is an anonymous visitor.
950 *
951 * @return bool
952 */
953 function isAnon() {
954 return !$this->isLoggedIn();
955 }
956
957 /**
958 * Check if a user is sysop
959 * Die with backtrace. Use User:isAllowed() instead.
960 * @deprecated
961 */
962 function isSysop() {
963 return $this->isAllowed( 'protect' );
964 }
965
966 /** @deprecated */
967 function isDeveloper() {
968 return $this->isAllowed( 'siteadmin' );
969 }
970
971 /** @deprecated */
972 function isBureaucrat() {
973 return $this->isAllowed( 'makesysop' );
974 }
975
976 /**
977 * Whether the user is a bot
978 * @todo need to be migrated to the new user level management sytem
979 */
980 function isBot() {
981 $this->loadFromDatabase();
982 return in_array( 'bot', $this->mRights );
983 }
984
985 /**
986 * Check if user is allowed to access a feature / make an action
987 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
988 * @return boolean True: action is allowed, False: action should not be allowed
989 */
990 function isAllowed($action='') {
991 $this->loadFromDatabase();
992 return in_array( $action , $this->mRights );
993 }
994
995 /**
996 * Load a skin if it doesn't exist or return it
997 * @todo FIXME : need to check the old failback system [AV]
998 */
999 function &getSkin() {
1000 global $IP;
1001 if ( ! isset( $this->mSkin ) ) {
1002 $fname = 'User::getSkin';
1003 wfProfileIn( $fname );
1004
1005 # get all skin names available
1006 $skinNames = Skin::getSkinNames();
1007
1008 # get the user skin
1009 $userSkin = $this->getOption( 'skin' );
1010 if ( $userSkin == '' ) { $userSkin = 'standard'; }
1011
1012 if ( !isset( $skinNames[$userSkin] ) ) {
1013 # in case the user skin could not be found find a replacement
1014 $fallback = array(
1015 0 => 'Standard',
1016 1 => 'Nostalgia',
1017 2 => 'CologneBlue');
1018 # if phptal is enabled we should have monobook skin that
1019 # superseed the good old SkinStandard.
1020 if ( isset( $skinNames['monobook'] ) ) {
1021 $fallback[0] = 'MonoBook';
1022 }
1023
1024 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
1025 $sn = $fallback[$userSkin];
1026 } else {
1027 $sn = 'Standard';
1028 }
1029 } else {
1030 # The user skin is available
1031 $sn = $skinNames[$userSkin];
1032 }
1033
1034 # Grab the skin class and initialise it. Each skin checks for PHPTal
1035 # and will not load if it's not enabled.
1036 require_once( $IP.'/skins/'.$sn.'.php' );
1037
1038 # Check if we got if not failback to default skin
1039 $className = 'Skin'.$sn;
1040 if( !class_exists( $className ) ) {
1041 # DO NOT die if the class isn't found. This breaks maintenance
1042 # scripts and can cause a user account to be unrecoverable
1043 # except by SQL manipulation if a previously valid skin name
1044 # is no longer valid.
1045 $className = 'SkinStandard';
1046 require_once( $IP.'/skins/Standard.php' );
1047 }
1048 $this->mSkin =& new $className;
1049 wfProfileOut( $fname );
1050 }
1051 return $this->mSkin;
1052 }
1053
1054 /**#@+
1055 * @param string $title Article title to look at
1056 */
1057
1058 /**
1059 * Check watched status of an article
1060 * @return bool True if article is watched
1061 */
1062 function isWatched( $title ) {
1063 $wl = WatchedItem::fromUserTitle( $this, $title );
1064 return $wl->isWatched();
1065 }
1066
1067 /**
1068 * Watch an article
1069 */
1070 function addWatch( $title ) {
1071 $wl = WatchedItem::fromUserTitle( $this, $title );
1072 $wl->addWatch();
1073 $this->invalidateCache();
1074 }
1075
1076 /**
1077 * Stop watching an article
1078 */
1079 function removeWatch( $title ) {
1080 $wl = WatchedItem::fromUserTitle( $this, $title );
1081 $wl->removeWatch();
1082 $this->invalidateCache();
1083 }
1084
1085 /**
1086 * Clear the user's notification timestamp for the given title.
1087 * If e-notif e-mails are on, they will receive notification mails on
1088 * the next change of the page if it's watched etc.
1089 */
1090 function clearNotification( &$title ) {
1091 global $wgUser, $wgUseEnotif;
1092
1093 if ( !$wgUseEnotif ) {
1094 return;
1095 }
1096
1097 $userid = $this->getID();
1098 if ($userid==0) {
1099 return;
1100 }
1101
1102 // Only update the timestamp if the page is being watched.
1103 // The query to find out if it is watched is cached both in memcached and per-invocation,
1104 // and when it does have to be executed, it can be on a slave
1105 // If this is the user's newtalk page, we always update the timestamp
1106 if ($title->getNamespace() == NS_USER_TALK &&
1107 $title->getText() == $wgUser->getName())
1108 {
1109 $watched = true;
1110 } elseif ( $this->getID() == $wgUser->getID() ) {
1111 $watched = $title->userIsWatching();
1112 } else {
1113 $watched = true;
1114 }
1115
1116 // If the page is watched by the user (or may be watched), update the timestamp on any
1117 // any matching rows
1118 if ( $watched ) {
1119 $dbw =& wfGetDB( DB_MASTER );
1120 $success = $dbw->update( 'watchlist',
1121 array( /* SET */
1122 'wl_notificationtimestamp' => 0
1123 ), array( /* WHERE */
1124 'wl_title' => $title->getDBkey(),
1125 'wl_namespace' => $title->getNamespace(),
1126 'wl_user' => $this->getID()
1127 ), 'User::clearLastVisited'
1128 );
1129 }
1130 }
1131
1132 /**#@-*/
1133
1134 /**
1135 * Resets all of the given user's page-change notification timestamps.
1136 * If e-notif e-mails are on, they will receive notification mails on
1137 * the next change of any watched page.
1138 *
1139 * @param int $currentUser user ID number
1140 * @access public
1141 */
1142 function clearAllNotifications( $currentUser ) {
1143 global $wgUseEnotif;
1144 if ( !$wgUseEnotif ) {
1145 return;
1146 }
1147 if( $currentUser != 0 ) {
1148
1149 $dbw =& wfGetDB( DB_MASTER );
1150 $success = $dbw->update( 'watchlist',
1151 array( /* SET */
1152 'wl_notificationtimestamp' => 0
1153 ), array( /* WHERE */
1154 'wl_user' => $currentUser
1155 ), 'UserMailer::clearAll'
1156 );
1157
1158 # we also need to clear here the "you have new message" notification for the own user_talk page
1159 # This is cleared one page view later in Article::viewUpdates();
1160 }
1161 }
1162
1163 /**
1164 * @access private
1165 * @return string Encoding options
1166 */
1167 function encodeOptions() {
1168 $a = array();
1169 foreach ( $this->mOptions as $oname => $oval ) {
1170 array_push( $a, $oname.'='.$oval );
1171 }
1172 $s = implode( "\n", $a );
1173 return $s;
1174 }
1175
1176 /**
1177 * @access private
1178 */
1179 function decodeOptions( $str ) {
1180 $a = explode( "\n", $str );
1181 foreach ( $a as $s ) {
1182 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1183 $this->mOptions[$m[1]] = $m[2];
1184 }
1185 }
1186 }
1187
1188 function setCookies() {
1189 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1190 if ( 0 == $this->mId ) return;
1191 $this->loadFromDatabase();
1192 $exp = time() + $wgCookieExpiration;
1193
1194 $_SESSION['wsUserID'] = $this->mId;
1195 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
1196
1197 $_SESSION['wsUserName'] = $this->mName;
1198 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
1199
1200 $_SESSION['wsToken'] = $this->mToken;
1201 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1202 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
1203 } else {
1204 setcookie( $wgDBname.'Token', '', time() - 3600 );
1205 }
1206 }
1207
1208 /**
1209 * Logout user
1210 * It will clean the session cookie
1211 */
1212 function logout() {
1213 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1214 $this->loadDefaults();
1215 $this->setLoaded( true );
1216
1217 $_SESSION['wsUserID'] = 0;
1218
1219 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1220 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1221
1222 # Remember when user logged out, to prevent seeing cached pages
1223 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
1224 }
1225
1226 /**
1227 * Save object settings into database
1228 */
1229 function saveSettings() {
1230 global $wgMemc, $wgDBname, $wgUseEnotif;
1231 $fname = 'User::saveSettings';
1232
1233 if ( wfReadOnly() ) { return; }
1234 $this->saveNewtalk();
1235 if ( 0 == $this->mId ) { return; }
1236
1237 $dbw =& wfGetDB( DB_MASTER );
1238 $dbw->update( 'user',
1239 array( /* SET */
1240 'user_name' => $this->mName,
1241 'user_password' => $this->mPassword,
1242 'user_newpassword' => $this->mNewpassword,
1243 'user_real_name' => $this->mRealName,
1244 'user_email' => $this->mEmail,
1245 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1246 'user_options' => $this->encodeOptions(),
1247 'user_touched' => $dbw->timestamp($this->mTouched),
1248 'user_token' => $this->mToken
1249 ), array( /* WHERE */
1250 'user_id' => $this->mId
1251 ), $fname
1252 );
1253 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1254 }
1255
1256 /**
1257 * Save value of new talk flag.
1258 */
1259 function saveNewtalk() {
1260 global $wgDBname, $wgMemc, $wgUseEnotif;
1261
1262 $fname = 'User::saveNewtalk';
1263
1264 if ( wfReadOnly() ) { return ; }
1265 $dbr =& wfGetDB( DB_SLAVE );
1266 $dbw =& wfGetDB( DB_MASTER );
1267 if ( $wgUseEnotif ) {
1268 if ( ! $this->getNewtalk() ) {
1269 # Delete the watchlist entry for user_talk page X watched by user X
1270 $dbw->delete( 'watchlist',
1271 array( 'wl_user' => $this->mId,
1272 'wl_title' => $this->getTitleKey(),
1273 'wl_namespace' => NS_USER_TALK ),
1274 $fname );
1275 if ( $dbw->affectedRows() ) {
1276 $changed = true;
1277 }
1278 if( !$this->mId ) {
1279 # Anon users have a separate memcache space for newtalk
1280 # since they don't store their own info. Trim...
1281 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1282 }
1283 }
1284 } else {
1285 if ($this->getID() != 0) {
1286 $field = 'user_id';
1287 $value = $this->getID();
1288 $key = false;
1289 } else {
1290 $field = 'user_ip';
1291 $value = $this->mName;
1292 $key = "$wgDBname:newtalk:ip:$this->mName";
1293 }
1294
1295 $dbr =& wfGetDB( DB_SLAVE );
1296 $dbw =& wfGetDB( DB_MASTER );
1297
1298 $res = $dbr->selectField('user_newtalk', $field,
1299 array($field => $value), $fname);
1300
1301 $changed = true;
1302 if ($res !== false && $this->mNewtalk == 0) {
1303 $dbw->delete('user_newtalk', array($field => $value), $fname);
1304 if ( $key ) {
1305 $wgMemc->set( $key, 0 );
1306 }
1307 } else if ($res === false && $this->mNewtalk == 1) {
1308 $dbw->insert('user_newtalk', array($field => $value), $fname);
1309 if ( $key ) {
1310 $wgMemc->set( $key, 1 );
1311 }
1312 } else {
1313 $changed = false;
1314 }
1315 }
1316
1317 # Update user_touched, so that newtalk notifications in the client cache are invalidated
1318 if ( $changed && $this->getID() ) {
1319 $dbw->update('user',
1320 /*SET*/ array( 'user_touched' => $this->mTouched ),
1321 /*WHERE*/ array( 'user_id' => $this->getID() ),
1322 $fname);
1323 $wgMemc->set( "$wgDBname:user:id:{$this->mId}", $this, 86400 );
1324 }
1325 }
1326
1327 /**
1328 * Checks if a user with the given name exists, returns the ID
1329 */
1330 function idForName() {
1331 $fname = 'User::idForName';
1332
1333 $gotid = 0;
1334 $s = trim( $this->mName );
1335 if ( 0 == strcmp( '', $s ) ) return 0;
1336
1337 $dbr =& wfGetDB( DB_SLAVE );
1338 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1339 if ( $id === false ) {
1340 $id = 0;
1341 }
1342 return $id;
1343 }
1344
1345 /**
1346 * Add user object to the database
1347 */
1348 function addToDatabase() {
1349 $fname = 'User::addToDatabase';
1350 $dbw =& wfGetDB( DB_MASTER );
1351 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1352 $dbw->insert( 'user',
1353 array(
1354 'user_id' => $seqVal,
1355 'user_name' => $this->mName,
1356 'user_password' => $this->mPassword,
1357 'user_newpassword' => $this->mNewpassword,
1358 'user_email' => $this->mEmail,
1359 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1360 'user_real_name' => $this->mRealName,
1361 'user_options' => $this->encodeOptions(),
1362 'user_token' => $this->mToken
1363 ), $fname
1364 );
1365 $this->mId = $dbw->insertId();
1366 }
1367
1368 function spreadBlock() {
1369 global $wgIP;
1370 # If the (non-anonymous) user is blocked, this function will block any IP address
1371 # that they successfully log on from.
1372 $fname = 'User::spreadBlock';
1373
1374 wfDebug( "User:spreadBlock()\n" );
1375 if ( $this->mId == 0 ) {
1376 return;
1377 }
1378
1379 $userblock = Block::newFromDB( '', $this->mId );
1380 if ( !$userblock->isValid() ) {
1381 return;
1382 }
1383
1384 # Check if this IP address is already blocked
1385 $ipblock = Block::newFromDB( $wgIP );
1386 if ( $ipblock->isValid() ) {
1387 # Just update the timestamp
1388 $ipblock->updateTimestamp();
1389 return;
1390 }
1391
1392 # Make a new block object with the desired properties
1393 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1394 $ipblock->mAddress = $wgIP;
1395 $ipblock->mUser = 0;
1396 $ipblock->mBy = $userblock->mBy;
1397 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1398 $ipblock->mTimestamp = wfTimestampNow();
1399 $ipblock->mAuto = 1;
1400 # If the user is already blocked with an expiry date, we don't
1401 # want to pile on top of that!
1402 if($userblock->mExpiry) {
1403 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1404 } else {
1405 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1406 }
1407
1408 # Insert it
1409 $ipblock->insert();
1410
1411 }
1412
1413 function getPageRenderingHash() {
1414 global $wgContLang;
1415 if( $this->mHash ){
1416 return $this->mHash;
1417 }
1418
1419 // stubthreshold is only included below for completeness,
1420 // it will always be 0 when this function is called by parsercache.
1421
1422 $confstr = $this->getOption( 'math' );
1423 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1424 $confstr .= '!' . $this->getOption( 'editsection' );
1425 $confstr .= '!' . $this->getOption( 'date' );
1426 $confstr .= '!' . $this->getOption( 'numberheadings' );
1427 $confstr .= '!' . $this->getOption( 'language' );
1428 $confstr .= '!' . $this->getOption( 'thumbsize' );
1429 // add in language specific options, if any
1430 $extra = $wgContLang->getExtraHashOptions();
1431 $confstr .= $extra;
1432
1433 $this->mHash = $confstr;
1434 return $confstr ;
1435 }
1436
1437 function isAllowedToCreateAccount() {
1438 return $this->isAllowed( 'createaccount' );
1439 }
1440
1441 /**
1442 * Set mDataLoaded, return previous value
1443 * Use this to prevent DB access in command-line scripts or similar situations
1444 */
1445 function setLoaded( $loaded ) {
1446 return wfSetVar( $this->mDataLoaded, $loaded );
1447 }
1448
1449 /**
1450 * Get this user's personal page title.
1451 *
1452 * @return Title
1453 * @access public
1454 */
1455 function getUserPage() {
1456 return Title::makeTitle( NS_USER, $this->mName );
1457 }
1458
1459 /**
1460 * Get this user's talk page title.
1461 *
1462 * @return Title
1463 * @access public
1464 */
1465 function getTalkPage() {
1466 $title = $this->getUserPage();
1467 return $title->getTalkPage();
1468 }
1469
1470 /**
1471 * @static
1472 */
1473 function getMaxID() {
1474 $dbr =& wfGetDB( DB_SLAVE );
1475 return $dbr->selectField( 'user', 'max(user_id)', false );
1476 }
1477
1478 /**
1479 * Determine whether the user is a newbie. Newbies are either
1480 * anonymous IPs, or the 1% most recently created accounts.
1481 * Bots and sysops are excluded.
1482 * @return bool True if it is a newbie.
1483 */
1484 function isNewbie() {
1485 return $this->isAnon() || $this->mId > User::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1486 }
1487
1488 /**
1489 * Check to see if the given clear-text password is one of the accepted passwords
1490 * @param string $password User password.
1491 * @return bool True if the given password is correct otherwise False.
1492 */
1493 function checkPassword( $password ) {
1494 global $wgAuth, $wgMinimalPasswordLength;
1495 $this->loadFromDatabase();
1496
1497 // Even though we stop people from creating passwords that
1498 // are shorter than this, doesn't mean people wont be able
1499 // to. Certain authentication plugins do NOT want to save
1500 // domain passwords in a mysql database, so we should
1501 // check this (incase $wgAuth->strict() is false).
1502 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1503 return false;
1504 }
1505
1506 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1507 return true;
1508 } elseif( $wgAuth->strict() ) {
1509 /* Auth plugin doesn't allow local authentication */
1510 return false;
1511 }
1512 $ep = $this->encryptPassword( $password );
1513 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1514 return true;
1515 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1516 return true;
1517 } elseif ( function_exists( 'iconv' ) ) {
1518 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1519 # Check for this with iconv
1520 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1521 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1522 return true;
1523 }
1524 }
1525 return false;
1526 }
1527
1528 /**
1529 * Initialize (if necessary) and return a session token value
1530 * which can be used in edit forms to show that the user's
1531 * login credentials aren't being hijacked with a foreign form
1532 * submission.
1533 *
1534 * @param mixed $salt - Optional function-specific data for hash.
1535 * Use a string or an array of strings.
1536 * @return string
1537 * @access public
1538 */
1539 function editToken( $salt = '' ) {
1540 if( !isset( $_SESSION['wsEditToken'] ) ) {
1541 $token = $this->generateToken();
1542 $_SESSION['wsEditToken'] = $token;
1543 } else {
1544 $token = $_SESSION['wsEditToken'];
1545 }
1546 if( is_array( $salt ) ) {
1547 $salt = implode( '|', $salt );
1548 }
1549 return md5( $token . $salt );
1550 }
1551
1552 /**
1553 * Generate a hex-y looking random token for various uses.
1554 * Could be made more cryptographically sure if someone cares.
1555 * @return string
1556 */
1557 function generateToken( $salt = '' ) {
1558 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1559 return md5( $token . $salt );
1560 }
1561
1562 /**
1563 * Check given value against the token value stored in the session.
1564 * A match should confirm that the form was submitted from the
1565 * user's own login session, not a form submission from a third-party
1566 * site.
1567 *
1568 * @param string $val - the input value to compare
1569 * @param string $salt - Optional function-specific data for hash
1570 * @return bool
1571 * @access public
1572 */
1573 function matchEditToken( $val, $salt = '' ) {
1574 return ( $val == $this->editToken( $salt ) );
1575 }
1576
1577 /**
1578 * Generate a new e-mail confirmation token and send a confirmation
1579 * mail to the user's given address.
1580 *
1581 * @return mixed True on success, a WikiError object on failure.
1582 */
1583 function sendConfirmationMail() {
1584 global $wgIP, $wgContLang;
1585 $url = $this->confirmationTokenUrl( $expiration );
1586 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1587 wfMsg( 'confirmemail_body',
1588 $wgIP,
1589 $this->getName(),
1590 $url,
1591 $wgContLang->timeanddate( $expiration, false ) ) );
1592 }
1593
1594 /**
1595 * Send an e-mail to this user's account. Does not check for
1596 * confirmed status or validity.
1597 *
1598 * @param string $subject
1599 * @param string $body
1600 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1601 * @return mixed True on success, a WikiError object on failure.
1602 */
1603 function sendMail( $subject, $body, $from = null ) {
1604 if( is_null( $from ) ) {
1605 global $wgPasswordSender;
1606 $from = $wgPasswordSender;
1607 }
1608
1609 require_once( 'UserMailer.php' );
1610 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1611
1612 if( $error == '' ) {
1613 return true;
1614 } else {
1615 return new WikiError( $error );
1616 }
1617 }
1618
1619 /**
1620 * Generate, store, and return a new e-mail confirmation code.
1621 * A hash (unsalted since it's used as a key) is stored.
1622 * @param &$expiration mixed output: accepts the expiration time
1623 * @return string
1624 * @access private
1625 */
1626 function confirmationToken( &$expiration ) {
1627 $fname = 'User::confirmationToken';
1628
1629 $now = time();
1630 $expires = $now + 7 * 24 * 60 * 60;
1631 $expiration = wfTimestamp( TS_MW, $expires );
1632
1633 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
1634 $hash = md5( $token );
1635
1636 $dbw =& wfGetDB( DB_MASTER );
1637 $dbw->update( 'user',
1638 array( 'user_email_token' => $hash,
1639 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1640 array( 'user_id' => $this->mId ),
1641 $fname );
1642
1643 return $token;
1644 }
1645
1646 /**
1647 * Generate and store a new e-mail confirmation token, and return
1648 * the URL the user can use to confirm.
1649 * @param &$expiration mixed output: accepts the expiration time
1650 * @return string
1651 * @access private
1652 */
1653 function confirmationTokenUrl( &$expiration ) {
1654 $token = $this->confirmationToken( $expiration );
1655 $title = Title::makeTitle( NS_SPECIAL, 'Confirmemail/' . $token );
1656 return $title->getFullUrl();
1657 }
1658
1659 /**
1660 * Mark the e-mail address confirmed and save.
1661 */
1662 function confirmEmail() {
1663 $this->loadFromDatabase();
1664 $this->mEmailAuthenticated = wfTimestampNow();
1665 $this->saveSettings();
1666 return true;
1667 }
1668
1669 /**
1670 * Is this user allowed to send e-mails within limits of current
1671 * site configuration?
1672 * @return bool
1673 */
1674 function canSendEmail() {
1675 return $this->isEmailConfirmed();
1676 }
1677
1678 /**
1679 * Is this user allowed to receive e-mails within limits of current
1680 * site configuration?
1681 * @return bool
1682 */
1683 function canReceiveEmail() {
1684 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1685 }
1686
1687 /**
1688 * Is this user's e-mail address valid-looking and confirmed within
1689 * limits of the current site configuration?
1690 *
1691 * If $wgEmailAuthentication is on, this may require the user to have
1692 * confirmed their address by returning a code or using a password
1693 * sent to the address from the wiki.
1694 *
1695 * @return bool
1696 */
1697 function isEmailConfirmed() {
1698 global $wgEmailAuthentication;
1699 $this->loadFromDatabase();
1700 if( $this->isAnon() )
1701 return false;
1702 if( !$this->isValidEmailAddr( $this->mEmail ) )
1703 return false;
1704 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1705 return false;
1706 return true;
1707 }
1708
1709 /**
1710 * @param array $groups list of groups
1711 * @return array list of permission key names for given groups combined
1712 * @static
1713 */
1714 function getGroupPermissions( $groups ) {
1715 global $wgGroupPermissions;
1716 $rights = array();
1717 foreach( $groups as $group ) {
1718 if( isset( $wgGroupPermissions[$group] ) ) {
1719 $rights = array_merge( $rights,
1720 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
1721 }
1722 }
1723 return $rights;
1724 }
1725
1726 /**
1727 * @param string $group key name
1728 * @return string localized descriptive name, if provided
1729 * @static
1730 */
1731 function getGroupName( $group ) {
1732 $key = "group-$group-name";
1733 $name = wfMsg( $key );
1734 if( $name == '' || $name == "&lt;$key&gt;" ) {
1735 return $group;
1736 } else {
1737 return $name;
1738 }
1739 }
1740
1741 /**
1742 * Return the set of defined explicit groups.
1743 * The * and 'user' groups are not included.
1744 * @return array
1745 * @static
1746 */
1747 function getAllGroups() {
1748 global $wgGroupPermissions;
1749 return array_diff(
1750 array_keys( $wgGroupPermissions ),
1751 array( '*', 'user' ) );
1752 }
1753
1754 }
1755
1756 ?>